package io.esirong.util;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.TextView;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @ClassName: MEditTextWatcher
 * @Description: 多对像协同鉴别监听(全部非空
 * @author: 黄嵘才(HuangRc)
 * @date: 2020/5/12
 */
public class MEditTextWatcher {

    private Callback callback;
    private List<TextView> views;
    private List<String> strings;

    public static MEditTextWatcher createWatch(TextView... views) {
        MEditTextWatcher textWatcher = new MEditTextWatcher();
        textWatcher.views = Arrays.asList(views);
        return textWatcher;

    }

    public void setCallback(Callback callback) {
        this.callback = callback;
        for (TextView textView : views) {
            textView.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    handleTextChanged(textView, s);
                }
            });
        }

    }


    public interface Callback {
        /**
         * 回调
         *
         * @param type 0 表示全部非空，-1表示有空
         * @param list
         */
        void call(int type, List<TextView> list);
    }

    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母、数字和汉字
        String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    private void handleTextChanged(TextView view, Editable s) {
        if (callback == null) {
            return;
        }

        boolean isAllNotEmpty = true;
        //检查所有控件，没有填写则立即返回
        for (TextView v : views) {
            CharSequence charSequence = v.getText();
            if (charSequence.length() < 0) {
                isAllNotEmpty = false;
                break;
            }

        }

        if (isAllNotEmpty) {
            callback.call(0, views);
        } else {
            //有空的
            callback.call(-1, views);
        }
    }

}
